np
In [1]:
import numpy as np
In [2]:
try:
np
except NameError:
print('Numpy not correctly imported')
2. Create a null vector Z
of size 10. Don't use [0, 0, ...] notation.
In [3]:
Z = np.zeros(10)
print(Z)
In [4]:
assert type(Z).__module__ == np.__name__
assert len(Z) == 10
assert sum(Z) == 0
3. Create a null vector of size 10 but the fifth value which is 1
In [5]:
Z = np.zeros(10)
Z[4] = 1
print(Z)
In [6]:
assert type(Z).__module__ == np.__name__
assert len(Z) == 10
assert sum(Z) == 1
4. Create a Numpy vector with values ranging from 10 to 49
In [8]:
Z = np.arange(10,50)
print(Z)
In [9]:
assert type(Z).__module__ == np.__name__
assert len(Z) == 40
assert sum(Z) == 1180
5. Reverse the vector from the previous task (first element becomes last)
In [10]:
Z = Z[::-1]
print(Z)
In [11]:
assert type(Z).__module__ == np.__name__
assert len(Z) == 40
assert sum(Z) == 1180
assert Z[0] == 49
assert Z[-1] == 10
6. Create a 3x3 matrix with values ranging from 0 to 8
In [12]:
Z = np.arange(9).reshape(3,3)
print(Z)
In [13]:
assert Z.shape == (3, 3)
assert np.all(sum(Z) == np.array([9, 12, 15]))
7. Find the indices of non-zero elements from [1,2,0,0,4,0] and store the result in nz
In [15]:
nz = np.array([1,2,0,0,4,0])
nz = (nz[nz != 0])
In [16]:
assert np.all(nz == np.array([1, 2, 4]))
8. Create a 3x3x3 (i.e. three dimensions with three values each) array with random values invariable Z
In [18]:
Z = np.random.random((3,3,3))
print(Z)
In [19]:
assert Z.shape == (3, 3, 3)
13. Create a 10x10 array with random values and find the minimum and maximum values and store them in Zmin
and Zmax
.
In [37]:
Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax)
In [39]:
z = Z.ravel()
idx = z.argsort()
assert z[idx[0]] == Zmin
assert z[idx[-1]] == Zmax
14. Create a random vector of size 30 and find the mean value using Numpy. Store the result into mean
In [50]:
Z = np.random.random(30)
mean = Z.mean()
print(mean)
In [54]:
accumulative = 0
for z in Z:
accumulative += z
assert mean - (accumulative/len(Z)) < 0.0001
15. Create a 8x8 matrix and fill it with a chessboard pattern (say, 1 == 'black' and 0 == 'white'). Use fancy indexing.
In [63]:
Z = np.zeros((8,8), dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)
16. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product)
In [66]:
Z = np.dot(np.ones((5,3)), np.ones((3,2)))
print(Z)
17. Given a array np.arange(11)
, negate all elements which are between 3 and 8, in place.
In [70]:
Z = np.arange(11)
Z[(3 < Z) & (Z <= 8)] *= -1
print(Z)